import React, {Component} from 'react';
import {Button, Space, Select} from 'antd';
//用户获取store中管理的状态
import store from "../../redux/store";
import {createIncrementAction,createDecrementAction} from "../../redux/count_action";

const {Option} = Select;

class Count extends Component {
    state = {
        selectNumber: 0
    }

    /*componentDidMount() {
        //检测redux中的状态变化，只要变化，就调用render
        store.subscribe(() => {
            this.setState({})
        })
    }*/

    //+
    increment = () => {
        let {selectNumber} = this.state;
        store.dispatch(createIncrementAction(selectNumber))
    }
    //-
    decrement = () => {
        let {selectNumber} = this.state;
        store.dispatch(createDecrementAction(selectNumber))
    }
    incrementIfOdd = () => {
        let {selectNumber} = this.state;
        let count = store.getState();
        if (count % 2 !== 0) {
            store.dispatch(createIncrementAction(selectNumber))
        }
    }
    incrementAsync = () => {
        let {selectNumber} = this.state;
        setTimeout(() => {
            store.dispatch(createIncrementAction(selectNumber))
        }, 1000);
    }

    //组件变换
    handleChange = (value) => {
        this.setState({
            selectNumber: value
        })
    }

    render() {
        return (
            <div>
                <h1>当前求和为:{store.getState()}</h1>
                <Space>
                    <Select style={{width: 300}}
                            onChange={this.handleChange}>
                        <Option value={1}>1</Option>
                        <Option value={2}>2</Option>
                        <Option value={3}>3</Option>
                    </Select>
                    <Button onClick={this.increment} type="primary">+</Button>
                    <Button onClick={this.decrement} type="primary">-</Button>
                    <Button onClick={this.incrementIfOdd} type="primary">奇数+</Button>
                    <Button onClick={this.incrementAsync} type="primary">异步加</Button>
                </Space>
            </div>
        );
    }
}

export default Count;